package ru.mti.edu.servlet;

import static ru.mti.edu.servlet.Constant.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ru.mti.edu.jdbc.JdbcUsing;

/**
 * Servlet implementation class ServletUsing
 */
public class ServletUsing extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("GET Method was requested!");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String login = request.getParameter("Login");
		String password = request.getParameter("Password");
		
		try {
			PrintWriter pw = response.getWriter();
			HttpSession session = request.getSession();
			if (JdbcUsing.isLogon(login, password)){
				session.setAttribute(IS_AUTH_SESSION_ATTRIBUTE_NAME, true);
				response.addCookie(new Cookie(LAST_LOGIN_COOKIE_NAME, login));
				pw.println("Authorization was succeed!");
			}
			else {
				session.setAttribute(IS_AUTH_SESSION_ATTRIBUTE_NAME, false);
				pw.println("Authorization was failed!");
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
		
	}

}
